package com.demo.order.mapper;

import com.demo.order.entity.SeckillOrder;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 秒杀订单Mapper接口
 */
@Mapper
public interface SeckillOrderMapper {    
    /**
     * 根据ID查询订单
     */
    SeckillOrder selectById(Long orderId);
    
    /**
     * 根据用户ID查询订单列表
     */
    List<SeckillOrder> selectByUserId(Long userId);
    
    /**
     * 根据状态查询订单列表
     */
    List<SeckillOrder> selectByStatus(Integer status);
    
    /**
     * 插入订单
     */
    int insert(SeckillOrder order);
    
    /**
     * 更新订单
     */
    int update(SeckillOrder order);
    
    /**
     * 删除订单
     */
    int deleteById(Long orderId);

    /**
     * 根据消息ID查询订单（用于幂等性控制）
     * @param messageId 消息ID
     * @return 订单信息
     */
    @Select("SELECT * FROM seckill_order WHERE message_id = #{messageId}")
    SeckillOrder selectByMessageId(@Param("messageId") String messageId);

    /**
     * 查询超时未支付的订单
     * @param currentTime 当前时间
     * @return 超时订单列表
     */
    @Select("SELECT * FROM seckill_order WHERE status = 0 AND expire_time < #{currentTime}")
    List<SeckillOrder> selectExpiredOrders(@Param("currentTime") LocalDateTime currentTime);

    /**
     * 批量取消超时订单
     * @param orderIds 订单ID列表
     * @return 更新数量
     */
    @Update("<script>" +
            "UPDATE seckill_order SET status = 2, update_time = NOW() " +
            "WHERE order_id IN " +
            "<foreach collection='orderIds' item='orderId' open='(' separator=',' close=')'>" +
            "#{orderId}" +
            "</foreach>" +
            "AND status = 0" +
            "</script>")
    int batchCancelOrders(@Param("orderIds") List<Long> orderIds);

    /**
     * 根据用户ID和商品ID查询订单
     * @param userId 用户ID
     * @param productId 商品ID
     * @return 订单列表
     */
    @Select("SELECT * FROM seckill_order WHERE user_id = #{userId} AND product_id = #{productId} ORDER BY create_time DESC")
    List<SeckillOrder> selectByUserAndProduct(@Param("userId") Long userId, @Param("productId") Long productId);

    /**
     * 更新订单支付状态
     * @param orderId 订单ID
     * @param payTime 支付时间
     * @return 更新数量
     */
    @Update("UPDATE seckill_order SET status = 1, pay_time = #{payTime}, update_time = NOW() " +
            "WHERE order_id = #{orderId} AND status = 0")
    int updatePayStatus(@Param("orderId") Long orderId, @Param("payTime") LocalDateTime payTime);
}